package repository

import (
	"SE/model"
	"gorm.io/gorm"
)

type PRepository struct {
	db *gorm.DB
}

func NewPRepository(db *gorm.DB) *PRepository {
	return &PRepository{db: db}
}

func (pr *PRepository) GetP(id string) ([]model.CarP, error) {
	var Ps []model.CarP
	result := pr.db.Where("p_id = ?", id).Limit(10).Find(&Ps)
	if result.Error != nil {
		return nil, result.Error
	}
	return Ps, nil
}
func (pr *PRepository) GetAllP() ([]model.P, error) {
	var Ps []model.P
	result := pr.db.Find(&Ps)
	if result.Error != nil {
		return nil, result.Error
	}
	return Ps, nil
}

func (pr *PRepository) AddP(newP model.P) error {
	result := pr.db.Create(&newP)
	if result.Error != nil {
		return result.Error
	}
	return nil
}

func (pr *PRepository) UpdateP(newP model.P) error {
	result := pr.db.Model(&newP).Where("id = ?", newP.Id).Updates(newP)
	if result.Error != nil {
		return result.Error
	}
	return nil
}

func (pr *PRepository) GetMyp(mid int) ([]model.P, error) {
	var Ps []model.P
	sql := "SELECT * from p where m_id = ?"
	result := pr.db.Raw(sql, mid).Scan(&Ps)
	if result.Error != nil {
		return nil, result.Error
	}
	return Ps, nil
}
